Page({
    data: {
        messages: [],
        inputValue: "",
        toView: "" // 控制滚动位置
    },

    onLoad() {
        // 页面加载时，读取本地存储的对话
        const history = wx.getStorageSync("chatHistory") || [];
        this.setData({
            messages: history,
            toView: history.length > 0 ? "msg-" + (history.length - 1) : ""
        });
    },

    // 输入框更新事件
    onInput(e) {
        this.setData({
            inputValue: e.detail.value
        });
    },

    // 发送消息
    sendMessage() {
        const text = this.data.inputValue.trim();
        if (!text) return;

        // 用户消息
        const userMsg = {
            role: "user",
            text
        };
        const newMessages = [...this.data.messages, userMsg];

        this.setData({
            messages: newMessages,
            inputValue: "",
            toView: "msg-" + (newMessages.length - 1)
        });

        wx.setStorageSync("chatHistory", newMessages);

        // 调用 AI
        this.callDashScope(text);
    },

    // 调用 AI
    callDashScope(prompt) {
        const appId = "2699f6a6ea8749b08fa9a6357bef9df1";
        const apiKey = "sk-00463e12ac034fd2b944cc07aa2c5bbd"; // ⚠️ 不要放生产

        wx.request({
            url: `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`,
            method: "POST",
            header: {
                "Authorization": `Bearer ${apiKey}`,
                "Content-Type": "application/json"
            },
            data: {
                input: {
                    prompt
                },
                parameters: {},
                debug: {}
            },
            success: (res) => {
                console.log("请求成功：", res);

                if (res.statusCode === 200 && res.data.output) {
                    const aiMsg = {
                        role: "ai",
                        text: res.data.output.text // 使用接口返回内容
                    };
                    const newMessages = [...this.data.messages, aiMsg];

                    this.setData({
                        messages: newMessages,
                        toView: "msg-" + (newMessages.length - 1)
                    });
                    wx.setStorageSync("chatHistory", newMessages);
                }
            },
            fail: (err) => {
                console.error("请求失败：", err);
            },
            complete: () => {
                console.log("请求结束");
            }
        });
    }
});
